#include "stdafx.h"

void CBumpTexture::Init(LPDIRECT3DDEVICE9 _Device)
{
	D3DXCreateTextureFromFile(_Device,TEXT("earth.tga"),&m_Texture);
	D3DXCreateTextureFromFile(_Device,TEXT("normal.tga"),&m_BumpTexture);

	LPD3DXBUFFER ErrorBuffer;
	D3DXCreateEffectFromFile(_Device,TEXT("bumptexture.es"),NULL,NULL,D3DXSHADER_DEBUG|D3DXSHADER_SKIPOPTIMIZATION,0,&m_LightEffect,&ErrorBuffer);
	if (ErrorBuffer)
	{
		char* Error = (char *)ErrorBuffer->GetBufferPointer();
		Error = Error;
		printf("%s",Error);
	}

	LPD3DXMESH PrevMesh;
	LPD3DXMESH NormalMesh;
	D3DXLoadMeshFromX(TEXT("sphereearth.x"),D3DXMESH_MANAGED,_Device,NULL,NULL,NULL,NULL,&PrevMesh);

	D3DVERTEXELEMENT9 decl[]=
	{
		{0, 0,  D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
		{0, 16, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
		{0, 24, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0},
		{0, 36, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0},
		D3DDECL_END()
	};

	PrevMesh->CloneMesh(D3DXMESH_MANAGED,decl,_Device,&m_Earth);
	D3DXComputeNormals(m_Earth,NULL);
	D3DXComputeTangent(m_Earth,0,0,0,true,NULL);
}

void CBumpTexture::Render(CEasyRender* _Render)
{
	m_LightEffect->SetTechnique("T0");

	D3DXMATRIXA16 matWorldViewProj;
	D3DXMATRIX matWorld,matView,matProj;

	D3DXMatrixIdentity(&matWorld);
	D3DXMatrixRotationZ(&matWorld,timeGetTime()/1000.0f);
	matView = *_Render->GetWorld2ViewMatrix();
	matProj = *_Render->GetProjectorMatrix();

	matWorldViewProj = matWorld * matView * matProj;
	m_LightEffect->SetMatrix("matWorldViewProj",&matWorldViewProj);
	m_LightEffect->SetMatrix("matWorld",&matWorld);

	D3DXVECTOR4 vecEyePos = *_Render->GetEyePosition();
	D3DXVECTOR4 lightDir( 1.0f, -1.0f, -1.0f, 1.0f );
	/*D3DXVECTOR4 lightDir = D3DXVECTOR4( cosf(timeGetTime()/350.0f), 1.0f,
		sinf(timeGetTime()/350.0f), 1.0f );*/
	m_LightEffect->SetVector("vecLightPos",&lightDir);
	m_LightEffect->SetVector("vecEyePos",&vecEyePos);

	m_LightEffect->SetTexture("BaseTexture",m_Texture);
	m_LightEffect->SetTexture("BumpTexture",m_BumpTexture);

	UINT PassCount;
	m_LightEffect->Begin(&PassCount,0);
	for (UINT i = 0;i < PassCount;++i)
	{
		m_LightEffect->BeginPass(i);
		
		m_Earth->DrawSubset(0);

		m_LightEffect->EndPass();
	}
	m_LightEffect->End();
}